﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;

using Baosight.ZNH.ZMCommon;
using Baosight.Platform.Core;
using Baosight.Platform.Core.UI.Controls;
using Baosight.Platform.Core.ServiceModel;

using Telerik.Windows.Controls;
using Telerik.Windows.Controls.Charting;

namespace Baosight.ZNH.ZMCE.UI
{
    public partial class ZMCEA0 : EFViewCmes
    {
        IList<CheckBox> checkedItems = new List<CheckBox>();
        private string chartType = "";

        public ZMCEA0()
        {
            InitializeComponent();

            this.fdBeginTime.Value = DateTime.Now.AddDays(-90).ToString(Common.DATETIME_FORMAT);
            this.fdEndTime.Value = DateTime.Now.ToString(Common.DATETIME_FORMAT);

            InitalChart(this.runChart, "运行数据分析");
            InitalChart(this.lifeChart, "使用寿命分析(单位：分钟)");

            this.Loaded += new RoutedEventHandler(ZMCEA0_Loaded);
        }

        #region 初始化，加载树目录

        /// <summary>
        /// 初始化，页面加载时，查询树目录节点
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void ZMCEA0_Loaded(object sender, RoutedEventArgs e)
        {
            EIInfo eiInfo = new EIInfo();
            eiInfo.Set("method", "initLoad");
            eiInfo.Set("service", "ZMCEA0");
            HttpServiceAgent agent = new HttpServiceAgent();
            agent.CallService(eiInfo, QueryDeviceSystemTreeCompleted, Common.DoWorkErrored);
        }

        /// <summary>
        /// 返回树目录节点数据，加载树目录
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void QueryDeviceSystemTreeCompleted(object sender, DoWorkCompletedEventArgs e)
        {
            if (e.EIInfo.Status == -1)
            {
                EFWindow.Alert("数据库查询数据错误，请检查服务器/数据库连接！");
                return;
            }
            else
            {
                EIInfo outInfo = e.EIInfo;

                EIBlock mineBlock = outInfo.GetBlock("mine");
                EIBlock systemBlock = outInfo.GetBlock("system");
                EIBlock unitBlock = outInfo.GetBlock("unit");

                if ((mineBlock != null) && (systemBlock != null) && (unitBlock != null))
                {
                    AddItemsToTree(mineBlock, systemBlock, unitBlock);
                    this.DeviceSystemTree.ExpandAll();
                }
                else
                {
                    return;
                }
            }
        }

        /// <summary>
        /// 添加矿井、生产系统、生产单元3级树目录结构
        /// </summary>
        /// <param name="mine"></param>
        /// <param name="system"></param>
        /// <param name="unit"></param>
        private void AddItemsToTree(EIBlock mine, EIBlock system, EIBlock unit)
        {
            IList<EIRow> mineRows = mine.GetRows();

            if (mineRows.Count > 0)
            {
                IDictionary<string, EFTreeItem> mineDic = new Dictionary<string, EFTreeItem>();
                IDictionary<string, EFTreeItem> systemDic = new Dictionary<string, EFTreeItem>();

                for (int i = 0; i < mineRows.Count; i++)
                {
                    EIRow row = mineRows[i];
                    EFTreeItem item = new EFTreeItem();
                    item.eHeader = row["fdName"];
                    item.ItemObject = row;
                    item.ExpandAll();
                    this.DeviceSystemTree.AddTreeItem(item);

                    string fdId = row["fdKeyId"].ToString().Trim();    //矿井ID
                    mineDic.Add(fdId, item);
                }

                AddChildItems(system, "fdMineId", "fdName", mineDic, systemDic);    //添加生产系统节点
                AddChildItems(unit, "fdProductionSystemId", "fdName", systemDic, null);      //添加生产单元节点
            }
        }

        /// <summary>
        /// 将Blcok中的节点添加到父节点下
        /// </summary>
        /// <param name="block"></param>
        /// <param name="parentIndex"></param>
        /// <param name="nameIndex"></param>
        /// <param name="parentDic"></param>
        /// <param name="childDic"></param>
        private void AddChildItems(EIBlock block, string parentIndex, string nameIndex,
            IDictionary<string, EFTreeItem> parentDic, IDictionary<string, EFTreeItem> childDic)
        {
            IList<EIRow> rows = block.GetRows();

            if (rows.Count > 0)
            {
                for (int i = 0; i < rows.Count; i++)
                {
                    string parentId = rows[i][parentIndex].ToString().Trim();

                    if (parentDic.ContainsKey(parentId))
                    {
                        EFTreeItem parentItem = parentDic[parentId];

                        EFTreeItem item = new EFTreeItem();
                        item.eHeader = rows[i][nameIndex];
                        item.ItemObject = rows[i];
                        item.ExpandAll();

                        parentItem.AddTreeItem(item);

                        if (childDic != null)
                        {
                            string fdId = rows[i]["fdKeyId"].ToString().Trim();
                            childDic.Add(fdId, item);
                        }
                    }
                }
            }
        }

        ///// <summary>
        ///// 加载树目录0级节点
        ///// </summary>
        ///// <param name="mine"></param>
        ///// <param name="system"></param>
        ///// <param name="device"></param>
        //private void AddItemsToTree(EIBlock mine, EIBlock system, EIBlock device)
        //{
        //    IList<EIRow> mineRows = mine.GetRows();

        //    if (mineRows.Count > 0)
        //    {
        //        for (int i = 0; i < mineRows.Count; i++)
        //        {
        //            EIRow row = mineRows[i];
        //            EFTreeItem item = new EFTreeItem();
        //            item.eHeader = row["fdName"];
        //            item.ItemObject = row;

        //            this.DeviceSystemTree.AddTreeItem(item);

        //            string fdId = row["fdKeyId"].ToString().Trim();    //矿井编号
        //            AddChildItemsToMine(item, fdId, system, device);    //
        //        }
        //    }
        //}

        ///// <summary>
        ///// 加载树目录1级节点
        ///// </summary>
        ///// <param name="item"></param>
        ///// <param name="mineNo"></param>
        ///// <param name="system"></param>
        ///// <param name="device"></param> 
        //private void AddChildItemsToMine(EFTreeItem item, string mineFdId, EIBlock system, EIBlock device)
        //{
        //    IList<EIRow> systemRows = system.GetRows();

        //    if (systemRows.Count > 0)
        //    {
        //        for (int i = 0; i < systemRows.Count; i++)
        //        {
        //            EIRow row = systemRows[i];

        //            if ((row["fdMineId"] != null) && (!row["fdMineId"].ToString().Trim().Equals("")))
        //            {
        //                string parentId = row["fdMineId"].ToString().Trim();
        //                if (parentId.Equals(mineFdId))
        //                {
        //                    EFTreeItem childItem = new EFTreeItem();
        //                    childItem.eHeader = row["fdName"];
        //                    childItem.ItemObject = row;
        //                    childItem.ExpandAll();
        //                    item.AddTreeItem(childItem);

        //                    string systemFdId = row["fdKeyId"].ToString().Trim();
        //                    AddChildItemsToSystem(childItem, systemFdId, device);
        //                }
        //            }
        //        }
        //    }
        //}

        ///// <summary>
        ///// 加载树目录2级节点
        ///// </summary>
        ///// <param name="item"></param>
        ///// <param name="mineNo"></param>
        ///// <param name="system"></param>
        ///// <param name="device"></param> 
        //private void AddChildItemsToSystem(EFTreeItem item, string systemFdId, EIBlock device)
        //{
        //    IList<EIRow> deviceRows = device.GetRows();

        //    if (deviceRows.Count > 0)
        //    {
        //        for (int i = 0; i < deviceRows.Count; i++)
        //        {
        //            EIRow row = deviceRows[i];

        //            if ((row["fdProductionSystemId"] != null) && (!row["fdProductionSystemId"].ToString().Trim().Equals("")))
        //            {
        //                string parentId = row["fdProductionSystemId"].ToString().Trim();
        //                if (parentId.Equals(systemFdId))
        //                {
        //                    EFTreeItem childItem = new EFTreeItem();
        //                    childItem.eHeader = row["fdEquipmentName"];
        //                    childItem.ItemObject = row;
        //                    childItem.ExpandAll();
        //                    item.AddTreeItem(childItem);
        //                }
        //            }
        //            else
        //            {
        //                EFTreeItem parentItem = item.GetParentTreeItem();

        //                EFTreeItem childItem = new EFTreeItem();
        //                childItem.eHeader = row["fdEquipmentName"];
        //                childItem.ItemObject = row;
        //                childItem.ExpandAll();
        //                parentItem.AddTreeItem(childItem);
        //            }
        //        }
        //    }
        //}

        #endregion

        #region 查询设备运行记录

        /// <summary>
        /// "查询"按钮响应事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        public override void OnQueryButtonClick(object sender, RoutedEventArgs e)
        {
            //base.OnQueryButtonClick(sender, e);

            string deviceNo = "";
            string deviceName = "";
            string startTime = "";
            string stopTime = "";

            if ((this.fdDeviceNo.Value != null) && (!this.fdDeviceNo.Value.ToString().Trim().Equals("")))
            {
                deviceNo = this.fdDeviceNo.Value.ToString().Trim();
            }

            if ((this.fdDeviceName.Value != null) && (!this.fdDeviceName.Value.ToString().Trim().Equals("")))
            {
                deviceName = this.fdDeviceName.Value.ToString().Trim();
            }

            if ((this.fdBeginTime != null))   //过滤开始日期可能输入的非法字符
            {
                string tmpStart = this.fdBeginTime.GetDataValue().ToString().Trim();
                this.fdBeginTime.Value = "";        //必须先置成""后，再赋值，才会在页面中生效
                this.fdBeginTime.Value = tmpStart;
            }

            if (this.fdEndTime != null)         //过滤结束日期可能输入的非法字符
            {
                string tmpEnd = this.fdEndTime.GetDataValue().ToString().Trim();
                this.fdEndTime.Value = "";      //必须先置成""后，再赋值，才会在页面中生效
                this.fdEndTime.Value = tmpEnd;
            }

            if (!GetDateTimePara(this.fdBeginTime, this.fdEndTime, ref startTime, ref stopTime))
            {
                return;
            }

            EIBlock block = new EIBlock("queryBlock");
            Common.AddColumnToBlock(block, "fdNo");
            Common.AddColumnToBlock(block, "fdName");
            Common.AddColumnToBlock(block, "fdStartTime");
            Common.AddColumnToBlock(block, "fdEndTime");

            EIRow row = new EIRow();
            row.Add("fdNo", deviceNo);
            row.Add("fdName", deviceName);
            row.Add("fdStartTime", startTime);
            row.Add("fdEndTime", stopTime);

            block.AddRow(row);

            QueryDeviceRunInfo(block);
        }

        /// <summary>
        /// 校验、获取起始、结束日期的查询条件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private bool GetDateTimePara(EFDataField fdStart, EFDataField fdEnd, ref string startTime, ref string stopTime)
        {
            startTime = "";
            stopTime = "";

            if ((fdStart != null) && (!fdStart.GetDataValue().ToString().Trim().Equals("")))
            {
                startTime = fdStart.Value.ToString().Trim() + " " + "00:00:00";
            }

            if ((fdEnd != null) && (!fdEnd.Value.ToString().Trim().Equals("")))
            {
                stopTime = fdEnd.Value.ToString().Trim() + " " + "23:59:59";
            }

            DateTime currentDate = DateTime.Parse(DateTime.Now.ToString(Common.DATETIME_FORMAT) + " " + "23:59:59");

            if ((!startTime.Equals("")) || (!stopTime.Equals("")))
            {
                if ((!startTime.Equals("")) && (!stopTime.Equals("")))
                {
                    DateTime beginTime = Convert.ToDateTime(startTime);
                    DateTime endTime = Convert.ToDateTime(stopTime);

                    if (beginTime.CompareTo(currentDate) > 0 || endTime.CompareTo(currentDate) > 0)
                    {
                        EFWindow.Alert("选择日期不能大于当前日期，请重新选择！");
                        return false;
                    }

                    if (beginTime.CompareTo(endTime) > 0)
                    {
                        EFWindow.Alert("开始日期不能大于结束日期，请重新选择！");
                        return false;
                    }
                }
                else if ((!startTime.Equals("")) && (stopTime.Equals("")))
                {
                    DateTime beginTime = Convert.ToDateTime(startTime);

                    if (beginTime.CompareTo(currentDate) > 0)
                    {
                        EFWindow.Alert("开始日期不能大于当前日期，请重新选择！");
                        return false;
                    }

                    fdEnd.Value = DateTime.Now.ToString(Common.DATETIME_FORMAT);
                    stopTime = DateTime.Now.ToString();
                }
                else if ((startTime.Equals("")) && (!stopTime.Equals("")))
                {
                    DateTime endTime = Convert.ToDateTime(stopTime);

                    if (endTime.CompareTo(currentDate) > 0)
                    {
                        EFWindow.Alert("结束日期不能大于当前日期，请重新选择！");
                        return false;
                    }
                }
            }

            return true;
        }

        /// <summary>
        /// 查询设备运行信息
        /// </summary>
        /// <param name="block"></param>
        private void QueryDeviceRunInfo(EIBlock block)
        {
            EIInfo inInfo = new EIInfo();

            inInfo.AddBlock(block);

            inInfo.Set("method", "query");
            inInfo.Set("service", "ZMCEA0");
            HttpServiceAgent agent = new HttpServiceAgent();
            agent.CallService(inInfo, QueryDeviceRunInfoCompleted, Common.DoWorkErrored);
        }

        /// <summary>
        /// 返回设备运行信息
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void QueryDeviceRunInfoCompleted(object sender, DoWorkCompletedEventArgs e)
        {
            EIInfo info = e.EIInfo;

            if (info.Status == -1)
            {
                EFWindow.Alert("数据库查询数据错误，请检查服务器/数据库连接！");
                return;
            }
            else
            {
                EIBlock equipmentBlock = info.GetBlock("equipment");
                EIBlock workLoadBlock = info.GetBlock("workLoad");
                EIBlock runBlock = info.GetBlock("run");
                EIBlock downBlock = info.GetBlock("down");
                EIBlock faultBlock = info.GetBlock("fault");

                if ((equipmentBlock != null) && (workLoadBlock != null) && (runBlock != null) && (downBlock != null) &&
                    (faultBlock != null))
                {
                    EIInfo dataInfo = GenerateDataInfo(equipmentBlock, workLoadBlock, runBlock, downBlock, faultBlock);

                    this.deviceGrid.ItemsSource = null;
                    this.deviceGrid.UpdateData(dataInfo);
                }
                else
                {
                    //EFWindow.Alert("block == null");
                    return;
                }
            }
        }

        /// <summary>
        /// 生成EiInfo结构的设备运行数据
        /// </summary>
        /// <param name="equipment"></param>
        /// <param name="workLoad"></param>
        /// <param name="operation"></param>
        /// <param name="down"></param>
        /// <param name="fault"></param>
        private EIInfo GenerateDataInfo(EIBlock equipment, EIBlock workLoad, EIBlock operation, EIBlock down, EIBlock fault)
        {
            EIInfo outInfo = new EIInfo();
            EIBlock block = new EIBlock("result");
            Common.AddColumnToBlock(block, "fdKeyId");
            Common.AddColumnToBlock(block, "fdNo");
            Common.AddColumnToBlock(block, "fdName");
            Common.AddColumnToBlock(block, "fdSystemName");
            Common.AddColumnToBlock(block, "fdMineName");
            Common.AddColumnToBlock(block, "fdSumWorkLoad");
            Common.AddColumnToBlock(block, "fdRunRate");
            Common.AddColumnToBlock(block, "fdFaultRate");
            Common.AddColumnToBlock(block, "fdFaultCount");
            Common.AddColumnToBlock(block, "fdFaultLatest");

            IList<EIRow> equipmentList = equipment.GetRows();

            if (equipmentList.Count > 0)
            {
                for (int i = 0; i < equipmentList.Count; i++)
                {
                    EIRow equipmentRow = equipmentList[i];

                    GetBlockValue(equipmentRow, workLoad, "fdSumWorkLoad");
                    GetRate(equipmentRow, operation, down);
                    GetBlockValue(equipmentRow, fault, "fdFaultCount");
                    GetBlockValue(equipmentRow, fault, "fdFaultLatest");

                    string lastestFault = equipmentRow["fdFaultLatest"].ToString().Trim();

                    if (!lastestFault.Equals("0"))
                    {
                        lastestFault = lastestFault.Substring(0, lastestFault.IndexOf('.'));
                        equipmentRow.Add("fdFaultLatest", lastestFault);
                    }

                    block.AddRow(equipmentRow);
                }
            }
            else
            {
                //修改Title、Chart
                this.itemsGridTitle.Text = "运行数据统计分析";
                this.lifeGridTitle.Text = "使用寿命数据统计分析";

                this.chartTitle.Text = "运行信息统计图";

                checkedItems.Clear();

                Common.ClearChart(this.runChart);
                Common.ClearChart(this.lifeChart);

                ClearEFGridData(this.deviceItemsInfoGrid, "runDataResult");
                ClearEFGridData(this.lifeInfoGrid, "lifeDataResult");

                this.deviceItemsGrid.Children.Clear();
            }

            block.Set(EIConstants.LimitKey, "10");      //设置EIblock的分页属性
            block.Set(EIConstants.OffsetKey, "0");
            block.Set(EIConstants.TotalRecordsKey, block.GetRowCount().ToString());
            block.Set(EIConstants.ShowCount, "true");

            outInfo.AddBlock(block);

            return outInfo;
        }

        /// <summary>
        /// 根据EIRow中的Id查询Block中的列值，并添加到EIRow中
        /// </summary>
        /// <param name="row"></param>
        /// <param name="block"></param>
        /// <param name="index"></param>
        private void GetBlockValue(EIRow row, EIBlock block, string index)
        {
            IList<EIRow> list = block.GetRows();

            if (list.Count > 0)                 //使用Linq方式进行查询
            {
                string equipmentId = row["fdKeyId"].ToString().Trim();
                //bool flag = (from a in list select a).Any(p => p["fdKeyId"].ToString().Trim().Equals(equipmentId));

                var query = (from item in list where equipmentId.Equals(item["fdKeyId"].ToString().Trim()) select item).ToList();
                //var query = list.Where(p => p["fdKeyId"].ToString().Trim().Equals(equipmentId));

                if (query.Count > 0)
                {
                    foreach (var item in query)
                    {
                        string unit = "";

                        if ((item["fdUnit"] != null) && (!item["fdUnit"].ToString().Trim().Equals("")))
                        {
                            unit = item["fdUnit"].ToString().Trim();
                        }

                        if ((item[index] != null) && (!item[index].ToString().Trim().Equals("")))
                        {
                            row.Add(index, item[index].ToString().Trim() + unit);
                            break;
                        }
                        else
                        {
                            row.Add(index, Common.ZERO_INT);
                            break;
                        }
                    }
                }
                else
                {
                    row.Add(index, Common.ZERO_INT);
                }
            }
            else
            {
                row.Add(index, Common.ZERO_INT);
            }
        }

        /// <summary>
        /// 计算开机率及故障率
        /// </summary>
        /// <param name="row"></param>
        /// <param name="operation"></param>
        /// <param name="down"></param>
        private void GetRate(EIRow row, EIBlock operation, EIBlock down)
        {
            double runTime = 0.0;
            double downTime = 0.0;
            double faultDownTime = 0.0;

            runTime = GetTime(row, operation, "fdSumRunTime");
            downTime = GetTime(row, down, "fdSumDownTime");
            faultDownTime = GetTime(row, down, "fdSumFaultDownTime");

            if (Common.IsZero(runTime))
            {
                row.Add("fdRunRate", Common.ZERO_RATIO);
                row.Add("fdFaultRate", Common.ZERO_RATIO);
            }
            else if (Common.IsValidateValue(runTime))
            {
                if (Common.IsZero(downTime))
                {
                    row.Add("fdRunRate", Common.HUNDRED_RATIO);
                    row.Add("fdFaultRate", Common.ZERO_RATIO);
                }
                else
                {
                    string ratio = (runTime * 100 / (runTime + downTime)).ToString();
                    row.Add("fdRunRate", ratio.Substring(0, ratio.IndexOf('.') + 3) + "%");

                    if (Common.IsZero(faultDownTime))
                    {
                        row.Add("fdFaultRate", Common.ZERO_RATIO);
                    }
                    else
                    {
                        string faultRatio = (faultDownTime * 100 / (runTime + downTime)).ToString();
                        row.Add("fdFaultRate", faultRatio.Substring(0, faultRatio.IndexOf('.') + 3) + "%");
                    }
                }
            }
        }

        /// <summary>
        /// 获取Block中的时间值
        /// </summary>
        /// <param name="row"></param>
        /// <param name="block"></param>
        /// <param name="index"></param>
        private double GetTime(EIRow row, EIBlock block, string index)
        {
            double tmpTime = 0.0;

            IList<EIRow> list = block.GetRows();

            if (list.Count > 0)
            {
                string equipmentId = row["fdKeyId"].ToString().Trim();
                var query = (from item in list where equipmentId.Equals(item["fdKeyId"].ToString().Trim()) select item).ToList();

                if (query.Count > 0)
                {
                    foreach (var item in query)
                    {
                        if ((item[index] != null) && (!item[index].ToString().Trim().Equals("")))
                        {
                            tmpTime = Double.Parse(item[index].ToString().Trim());
                            break;
                        }
                        else
                        {
                            break;
                        }
                    }
                }
            }

            return tmpTime;
        }

        #endregion

        #region 动态加载设备分析项

        /// <summary>
        /// 鼠标点击EFGrid中的记录时的响应事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void deviceGrid_SelectionChanged(object sender, SelectionChangeEventArgs e)
        {
            EIRow selectRow = this.deviceGrid.EIBlock.GetRow(this.deviceGrid.SelectedIndex);

            if (selectRow != null)
            {
                this.itemsGridTitle.Text = selectRow["fdName"].ToString().Trim() + "运行数据统计分析";
                this.lifeGridTitle.Text = selectRow["fdName"].ToString().Trim() + "使用寿命数据统计分析";
                this.chartTitle.Text = selectRow["fdName"].ToString().Trim() + "相关信息统计图";

                checkedItems.Clear();

                Common.ClearChart(this.runChart);
                Common.ClearChart(this.lifeChart);

                ClearEFGridData(this.deviceItemsInfoGrid, "runDataResult");
                ClearEFGridData(this.lifeInfoGrid, "lifeDataResult");

                this.deviceItemsGrid.Children.Clear();

                QueryDeviceItems(selectRow);
            }
            else
            {
                return;
            }
        }

        /// <summary>
        /// 查询设备分析项及寿命统计信息
        /// </summary>
        /// <param name="selectRow"></param>
        private void QueryDeviceItems(EIRow selectRow)
        {
            EIInfo inInfo = new EIInfo();

            EIBlock block = new EIBlock("queryBlock");
            Common.AddColumnToBlock(block, "fdKeyIds");

            EIRow _row = new EIRow();
            _row.Add("fdKeyIds", selectRow["fdKeyId"]);
            block.AddRow(_row);

            block.AddRow(_row);
            inInfo.AddBlock(block);

            inInfo.Set("method", "queryDeviceItems");
            inInfo.Set("service", "ZMCEA0");
            HttpServiceAgent agent = new HttpServiceAgent();
            agent.CallService(inInfo, QueryDeviceItemsCompleted, Common.DoWorkErrored);
        }

        /// <summary>
        /// 返回设备分析项信息
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void QueryDeviceItemsCompleted(object sender, DoWorkCompletedEventArgs e)
        {
            EIInfo info = e.EIInfo;

            if (info.Status == -1)
            {
                return;
            }
            else
            {
                EIBlock block = info.GetBlock("item");
                EIBlock lifeBlock = info.GetBlock("run");     //寿命分析信息

                if (block != null && lifeBlock != null)
                {
                    IList<EIRow> itemList = block.GetRows();

                    BindItemsToGrid(this.deviceItemsGrid, itemList);
                    BindDataToLifeGrid(this.lifeInfoGrid, lifeBlock);
                }
                else
                {
                    return;
                }


            }
        }

        /// <summary>
        /// 将设备分析项信息绑定到Grid中
        /// </summary>
        /// <param name="gridName"></param>
        /// <param name="list"></param>
        private void BindItemsToGrid(Grid gridName, IList<EIRow> list)
        {
            gridName.Children.Clear();

            int count = list.Count;

            if (count > 0)
            {
                if (count > 4)
                {
                    if (count % 4 == 0)     //每行保存4个条目
                    {
                        DivRowAndColumn(gridName, count / 4, 4);    //条目数为4的整数倍
                    }
                    else
                    {
                        DivRowAndColumn(gridName, count / 4 + 1, 4);    //条目数不为4的整数倍，多添加一行
                    }
                }
                else        //默认划分为1行4列
                {
                    DivRowAndColumn(gridName, 1, 4);
                }

                AddItemsToGrid(gridName, list);
            }
            else
            {
                return;
            }
        }

        /// <summary>
        /// 将指定的Grid划分成行列
        /// </summary>
        /// <param name="gridName"></param>
        /// <param name="rowCount"></param>
        /// <param name="colCount"></param>
        private void DivRowAndColumn(Grid gridName, int rowCount, int colCount)
        {
            if (rowCount <= 0 || colCount <= 0)
            {
                rowCount = 1;
                colCount = 1;
            }

            for (int i = 0; i < rowCount; i++)
            {
                gridName.RowDefinitions.Insert(i, new RowDefinition() { Height = GridLength.Auto });
            }
            for (int j = 0; j < colCount; j++)
            {
                gridName.ColumnDefinitions.Insert(j, new ColumnDefinition() { Width = new GridLength(200) });
            }
        }

        /// <summary>
        /// 添加分析项目到Grid中
        /// </summary>
        /// <param name="gridName"></param>
        /// <param name="rowCount"></param>
        /// <param name="colCount"></param>
        private void AddItemsToGrid(Grid gridName, IList<EIRow> list)
        {
            int rowIndex = 0;
            int colIndex = 0;

            for (int i = 0; i < list.Count; i++)
            {
                StackPanel stack = new StackPanel()
                {
                    Orientation = Orientation.Horizontal,
                    HorizontalAlignment = HorizontalAlignment.Stretch,
                    VerticalAlignment = VerticalAlignment.Stretch,
                };

                CheckBox check = new CheckBox() { DataContext = list[i], Tag = "" };
                check.IsChecked = false;
                check.Click += new RoutedEventHandler(DeviceItemClick);

                TextBlock text = new TextBlock() { Text = list[i]["fdName"].ToString() };

                stack.Children.Add(check);
                stack.Children.Add(text);

                stack.SetValue(Grid.RowProperty, rowIndex);
                stack.SetValue(Grid.ColumnProperty, colIndex++);

                gridName.Children.Add(stack);

                if (colIndex == 4)
                {
                    colIndex = 0; rowIndex++;
                }
            }
        }

        #endregion

        #region 刷新寿命分析数据及设备分析项目数据

        /// <summary>
        /// 刷新设备寿命分析数据
        /// </summary>
        /// <param name="gridName"></param>
        /// <param name="block"></param>
        private void BindDataToLifeGrid(EFGrid gridName, EIBlock block)
        {
            ClearEFGridData(this.lifeInfoGrid, "lifeDataResult");

            IList<EIRow> list = block.GetRows();

            if (list.Count > 0)
            {
                EIInfo dataInfo = new EIInfo();
                EIBlock dataBlock = new EIBlock("lifeDataResult");
                Common.AddColumnToBlock(dataBlock, "fdName");
                Common.AddColumnToBlock(dataBlock, "fdDeviceLifetime");
                Common.AddColumnToBlock(dataBlock, "fdSumRunTime");
                Common.AddColumnToBlock(dataBlock, "fdRemainTime");
                Common.AddColumnToBlock(dataBlock, "fdDiscardTime");

                for (int i = 0; i < list.Count; i++)
                {
                    EIRow row = list[i];

                    CalLifeData(row);
                    Common.DecimalFilter(row, "fdDeviceLifetime", 2);
                    Common.DecimalFilter(row, "fdSumRunTime", 2);
                    Common.DecimalFilter(row, "fdRemainTime", 2);

                    dataBlock.AddRow(row);
                }

                dataInfo.AddBlock(dataBlock);

                ClearEFGridData(this.lifeInfoGrid, "lifeDataResult");
                this.lifeInfoGrid.UpdateData(dataInfo);

                BindDataToLifeChart(dataBlock, this.lifeChart, chartType);
            }
        }

        /// <summary>
        /// 计算设备寿命分析项计算数据
        /// </summary>
        /// <param name="row"></param>
        private void CalLifeData(EIRow row)
        {
            double lifeTime = 0;
            double runTime = 0;
            if (row["fdDeviceLifetime"] != null)
            {
                lifeTime = Double.Parse(row["fdDeviceLifetime"].ToString().Trim()) * 60;
            }//寿命转换为分钟
            if (row["fdSumRunTime"] != null)
            {
                runTime = Double.Parse(row["fdSumRunTime"].ToString().Trim());
            }
            double remainTime = lifeTime - runTime;

            if (remainTime > Common.EPSINON)
            {
                string remain = remainTime.ToString();
                row.Add("fdRemainTime", remain);
                //row.Add("fdRemainTime", remain.Substring(0, remain.IndexOf('.') + 3));

                DateTime currentTime = DateTime.Now;
                DateTime endTime = currentTime.AddMinutes(remainTime);

                row.Add("fdDiscardTime", endTime.ToString().Trim());
            }
            else
            {
                row.Add("fdRemainTime", Common.ZERO_INT);
                row.Add("fdDiscardTime", "已报废！");
            }
        }

        /// <summary>
        /// 勾选设备分析项时的响应事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void DeviceItemClick(object sender, RoutedEventArgs e)
        {
            CheckBox selectedBox = sender as CheckBox;

            if (selectedBox == null)
            {
                return;
            }

            ClearEFGridData(this.deviceItemsInfoGrid, "runDataResult");

            if (selectedBox.IsChecked == false)
            {
                checkedItems.Remove(selectedBox);

                if (checkedItems.Count == 0)
                {
                    Common.ClearChart(this.runChart);
                    ClearEFGridData(this.deviceItemsInfoGrid, "runDataResult");

                    return;
                }
            }
            else
            {
                checkedItems.Add(selectedBox);
            }

            QueryItemsInfo(checkedItems);

        }

        /// <summary>
        /// 查询设备分析项运行数据信息
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void QueryItemsInfo(IList<CheckBox> items)
        {
            EIInfo eiInfo = new EIInfo();
            EIBlock block = new EIBlock("checkedBlock");
            Common.AddColumnToBlock(block, "fdProductionUnitsId");   //生产单元ID
            Common.AddColumnToBlock(block, "fdVariableId");         //变量ID
            eiInfo.AddBlock(block);

            if (items.Count > 0)
            {
                string tmpEquipmentId = "'";
                string tmpVariableId = "'";

                for (int i = 0; i < items.Count; i++)
                {
                    EIRow checkRow = items[i].DataContext as EIRow;

                    if (i == 0)
                    {
                        tmpEquipmentId = tmpEquipmentId + checkRow["fdProductionUnitsId"].ToString().Trim();
                        tmpVariableId = tmpVariableId + checkRow["fdKeyId"].ToString().Trim();
                    }
                    else
                    {
                        tmpEquipmentId = tmpEquipmentId + "', '" + checkRow["fdProductionUnitsId"].ToString().Trim();
                        tmpVariableId = tmpVariableId + "', '" + checkRow["fdKeyId"].ToString().Trim();
                    }
                }

                tmpEquipmentId = tmpEquipmentId + "'";
                tmpVariableId = tmpVariableId + "'";

                EIRow row = new EIRow();

                row.Add("fdProductionUnitsId", tmpEquipmentId);
                row.Add("fdVariableId", tmpVariableId);

                block.AddRow(row);
            }

            eiInfo.Set("method", "queryItemsInfo");
            eiInfo.Set("service", "ZMCEA0");

            HttpServiceAgent agent = new HttpServiceAgent();
            agent.CallService(eiInfo, QueryItemsInfoCompleted, Common.DoWorkErrored);
        }

        /// <summary>
        /// 返回设备分析项运行数据信息
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void QueryItemsInfoCompleted(object sender, DoWorkCompletedEventArgs e)
        {
            EIInfo info = e.EIInfo;

            if (info.Status == -1)
            {
                //EFWindow.Alert("后台返回设备分析项数据信息出错，出错函数：QueryItemsInfoCompleted！");
                return;
            }
            else
            {
                EIBlock maxBlock = info.GetBlock("max");
                EIBlock minBlock = info.GetBlock("min");

                if (maxBlock != null && minBlock != null)
                {
                    EIInfo dataInfo = GenerateItemDataInfo(maxBlock, minBlock);

                    ClearEFGridData(this.deviceItemsInfoGrid, "runDataResult");
                    this.deviceItemsInfoGrid.UpdateData(dataInfo);

                    BindDataToRunChart(dataInfo.GetBlock("runDataResult"), this.runChart, chartType);
                }
            }
        }

        /// <summary>
        /// 生成设备分析项运行Grid数据
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private EIInfo GenerateItemDataInfo(EIBlock max, EIBlock min)
        {
            EIInfo info = new EIInfo();
            EIBlock block = new EIBlock("runDataResult");
            Common.AddColumnToBlock(block, "fdProductionUnitsId");
            Common.AddColumnToBlock(block, "fdProductionUnitNo");
            Common.AddColumnToBlock(block, "fdProductionUnitName");
            Common.AddColumnToBlock(block, "fdVariableName");
            Common.AddColumnToBlock(block, "fdVariableUnit");
            Common.AddColumnToBlock(block, "fdMaxValue");
            Common.AddColumnToBlock(block, "fdMaxRecordtime");
            Common.AddColumnToBlock(block, "fdMinValue");
            Common.AddColumnToBlock(block, "fdMinRecordtime");
            Common.AddColumnToBlock(block, "fdAvgValue");

            IList<EIRow> maxList = max.GetRows();
            IList<EIRow> minList = min.GetRows();

            if (maxList.Count > 0 || minList.Count > 0)
            {
                for (int i = 0; i < maxList.Count; i++)
                {
                    EIRow row = maxList[i];

                    GetLatestRecord(row, maxList, "fdMaxRecordtime");

                    //var query = (from item in list where equipmentId.Equals(item["fdKeyId"].ToString().Trim()) select item).ToList();
                    var query = minList.Where(p => p["fdProductionUnitsId"].ToString().Trim().Equals(row["fdProductionUnitsId"].ToString().Trim()))
                                    .Where(p => p["fdVariableId"].ToString().Trim().Equals(row["fdVariableId"].ToString().Trim())).ToList();

                    if (query.Count > 0)
                    {
                        foreach (var item in query)
                        {
                            row.Add("fdMinValue", item["fdMinValue"].ToString().Trim());
                            row.Add("fdMinRecordtime", item["fdMinRecordtime"].ToString().Trim());

                            GetLatestRecord(row, maxList, "fdMaxRecordtime");   //查询最近的时刻
                            break;                        
                        } 
                    }

                    Common.DecimalFilter(row, "fdMaxValue", 2);
                    Common.DecimalFilter(row, "fdMinValue", 2);
                    Common.DecimalFilter(row, "fdAvgValue", 2);

                    block.AddRow(row);
                }
            }

            info.AddBlock(block);

            return info;
        }

        /// <summary>
        /// 获取最近的数据记录
        /// </summary>
        /// <param name="row"></param>
        /// <param name="list"></param>
        /// <param name="index"></param>
        private void GetLatestRecord(EIRow row, IList<EIRow> list, string index)
        {
            if (list.Count > 0)
            {
                //var query = (from item in list where equipmentId.Equals(item["fdKeyId"].ToString().Trim()) select item).ToList();
                var query = list.Where(p => p["fdProductionUnitsId"].ToString().Trim().Equals(row["fdProductionUnitsId"].ToString().Trim()))
                                .Where(p => p["fdVariableId"].ToString().Trim().Equals(row["fdVariableId"].ToString().Trim())).ToList();

                if (query.Count > 0)
                {
                    foreach (var item in query)
                    {
                        string minRecordTime = item[index].ToString().Trim();

                        DateTime curValue = Convert.ToDateTime(minRecordTime);
                        DateTime preValue = Convert.ToDateTime(row[index].ToString().Trim());

                        if (curValue.CompareTo(preValue) > 0)
                        {
                            row.Add(index, minRecordTime);
                        }
                    }
                }
                else
                {
                    row.Add(index, Common.ZERO_INT); 
                }
            }
        }

        #endregion

        #region 刷新运行数据统计分析图及寿命统计分析图

        /// <summary>
        /// 初始化RadChart图
        /// </summary>
        /// <param name="chart"></param>
        /// <param name="title"></param>
        private void InitalChart(RadChart chart, string title)
        {
            chart.DefaultView.ChartTitle.Content = title;
            chart.DefaultView.ChartTitle.FontSize = 12;

            chart.DefaultView.ChartLegend.Header = "";
            chart.DefaultView.ChartLegend.FontSize = 8;
            chart.DefaultView.ChartLegend.MaxWidth = 100;

            chart.DefaultView.ChartArea.FontSize = 8;

            chart.DefaultView.ChartArea.AxisX.LayoutMode = AxisLayoutMode.Inside;
            chart.DefaultView.ChartArea.AxisX.AutoRange = true;
            chart.DefaultView.ChartArea.AxisX.LabelRotationAngle = 45;
            chart.DefaultView.ChartArea.AxisX.DefaultLabelFormat = "MMM-yy";

            chart.DefaultView.ChartArea.AxisY.AutoRange = true;
            chart.DefaultView.ChartArea.AxisY.DefaultLabelFormat = "#VAL ";
            chart.DefaultView.ChartArea.AxisY.MajorGridLinesVisibility = Visibility.Visible;
            chart.DefaultView.ChartArea.AxisY.MinorGridLinesVisibility = Visibility.Visible;
            chart.DefaultView.ChartArea.AxisY.StripLinesVisibility = Visibility.Visible;

            chart.Visibility = Visibility.Visible;
        }

        /// <summary>
        /// 刷新寿命分析图表的数据
        /// </summary>
        /// <param name="chart"></param>
        /// <param name="title"></param>
        private void BindDataToLifeChart(EIBlock block, RadChart chartName, string type)
        {
            //string title = "使用寿命分析";
            //InitalChart(chartName, title);

            if (chartName.DefaultView.ChartArea.DataSeries != null)
            {
                chartName.DefaultView.ChartArea.DataSeries.Clear();
            }

            chartName.DefaultView.ChartLegend.Header = "";

            IList<EIRow> rowList = block.GetRows();

            if (rowList.Count > 0)
            {
                chartName.DefaultView.ChartArea.DataSeries.Add(GenerateSerie(rowList, type));
            }
        }

        /// <summary>
        /// 刷新运行统计分析图表的数据
        /// </summary>
        /// <param name="chart"></param>
        /// <param name="title"></param>
        private void BindDataToRunChart(EIBlock block, RadChart chartName, string chartType)
        {
            //string title = "运行数据分析";
            //InitalChart(chartName, title);

            if (chartName.DefaultView.ChartArea.DataSeries != null)
            {
                chartName.DefaultView.ChartArea.AdditionalYAxes.Clear();
                chartName.DefaultView.ChartArea.DataSeries.Clear();
            }

            chartName.DefaultView.ChartLegend.Header = "";

            IList<EIRow> rowList = block.GetRows();

            if (rowList.Count > 0)
            {
                if (!chartType.Equals(Common.CHART_PIE))
                {
                    for (int i = 0; i < rowList.Count; i++)
                    {
                        EIRow row = rowList[i];

                        if (i > 0)
                        {
                            int j = i - 1;

                            chartName.DefaultView.ChartArea.AdditionalYAxes.Add(new AxisY());
                            chartName.DefaultView.ChartArea.AdditionalYAxes[j].AxisName = row["fdVariableName"].ToString().Trim();
                            chartName.DefaultView.ChartArea.AdditionalYAxes[j].AutoRange = true;
                        }
                        else
                        {
                            chartName.DefaultView.ChartArea.AxisY.AxisName = row["fdVariableName"].ToString().Trim();

                        }
                        chartName.DefaultView.ChartArea.DataSeries.Add(GenerateSeries(row, chartType));
                    }
                }
                else
                {
                    chartName.DefaultView.ChartArea.DataSeries.Add(GenerateSeries(rowList[0], chartType));
                }
            }
        }

        /// <summary>
        /// 生成刷新寿命分析图表的柱状图
        /// </summary>
        /// <param name="chart"></param>
        /// <param name="title"></param>
        private DataSeries GenerateSerie(IList<EIRow> list, string type)
        {
            DataSeries series = new DataSeries();

            switch (type)
            {
                case "Bar":
                    series.Definition = new BarSeriesDefinition();
                    AddLifeDataToDataSeries(series, list);
                    break;
                case "Horizontal Bar":
                    series.Definition = new HorizontalBarSeriesDefinition();
                    AddLifeDataToDataSeries(series, list);
                    break;
                case "Line":
                    series.Definition = new LineSeriesDefinition();
                    AddLifeDataToDataSeries(series, list);
                    break;
                case "Pie":
                    series.Definition = new PieSeriesDefinition();
                    series.Definition.AxisName = string.Empty;

                    EIRow row = list[0];
                    series.Definition.ShowItemLabels = true;
                    series.Definition.ItemLabelFormat = "#VAL ";

                    series.LegendLabel = row["fdName"].ToString().Trim();

                    double sumRunTime = Double.Parse(row["fdSumRunTime"].ToString().Trim());
                    double fdRemainTime = Double.Parse(row["fdRemainTime"].ToString().Trim());

                    series.Add(new DataPoint(sumRunTime) { LegendLabel = "已用寿命" });
                    series.Add(new DataPoint(fdRemainTime) { LegendLabel = "剩余寿命" });

                    break;
                default:
                    series.Definition = new BarSeriesDefinition();
                    AddLifeDataToDataSeries(series, list);
                    break;
            }

            return series;
        }

        /// <summary>
        /// 添加寿命分析图表数据项
        /// </summary>
        /// <param name="series"></param>
        /// <param name="list"></param>
        private void AddLifeDataToDataSeries(DataSeries series, IList<EIRow> list)
        {
            series.Definition.AxisName = string.Empty;
            for (int i = 0; i < list.Count; i++)
            {
                EIRow row = list[i];
                series.LegendLabel = row["fdName"].ToString().Trim();
                string _fdDeviceLifetime = "0";
                string _fdSumRunTime = "0";
                string _fdRemainTime = "0";

                if (null != row["fdDeviceLifetime"] && !"".Equals(row["fdDeviceLifetime"].ToString().Trim()))
                {
                    _fdDeviceLifetime = row["fdDeviceLifetime"].ToString().Trim();
                }

                if (null != row["fdSumRunTime"] && !"".Equals(row["fdSumRunTime"].ToString().Trim()))
                {
                    _fdSumRunTime = row["fdSumRunTime"].ToString().Trim();
                }

                if (null != row["fdRemainTime"] && !"".Equals(row["fdRemainTime"].ToString().Trim()))
                {
                    _fdRemainTime = row["fdRemainTime"].ToString().Trim();
                }

                double lifeTime = Double.Parse(_fdDeviceLifetime) * 60;
                double sumRunTime = Double.Parse(_fdSumRunTime);
                double fdRemainTime = Double.Parse(_fdRemainTime);

                series.Add(new DataPoint(lifeTime) { XCategory = "使用寿命" });
                series.Add(new DataPoint(sumRunTime) { XCategory = "运行时间累计" });
                series.Add(new DataPoint(fdRemainTime) { XCategory = "剩余时间" });
            }
        }

        /// <summary>
        /// 生成运行统计分析图表的柱状图
        /// </summary>
        /// <param name="chart"></param>
        /// <param name="title"></param>
        private DataSeries GenerateSeries(EIRow row, string type)
        {
            DataSeries series = new DataSeries();

            switch (type)
            {
                case "Bar":
                    series.Definition = new BarSeriesDefinition();
                    AddRunDataToDataSeries(series, row);
                    break;
                case "Horizontal Bar":
                    series.Definition = new HorizontalBarSeriesDefinition();
                    AddRunDataToDataSeries(series, row);
                    break;
                case "Line":
                    series.Definition = new LineSeriesDefinition();
                    AddRunDataToDataSeries(series, row);
                    break;
                case "Pie":
                    series.Definition = new PieSeriesDefinition();
                    series.Definition.AxisName = string.Empty;

                    series.Definition.ShowItemLabels = true;
                    series.Definition.ItemLabelFormat = "#VAL ";

                    double maxValue = Double.Parse(row["fdMaxValue"].ToString().Trim());
                    double minValue = Double.Parse(row["fdMinValue"].ToString().Trim());
                    double avgValue = Double.Parse(row["fdAvgValue"].ToString().Trim());

                    series.Add(new DataPoint(maxValue) { LegendLabel = row["fdVariableName"].ToString().Trim() + "最大值" });
                    series.Add(new DataPoint(minValue) { LegendLabel = row["fdVariableName"].ToString().Trim() + "最小值" });
                    series.Add(new DataPoint(avgValue) { LegendLabel = row["fdVariableName"].ToString().Trim() + "平均值" });

                    break;
                default:
                    series.Definition = new BarSeriesDefinition();
                    AddRunDataToDataSeries(series, row);
                    break;
            }
            //series.Definition.AxisName = string.Empty;

            return series;
        }

        /// <summary>
        /// 生成运行统计分析图表的柱状图
        /// </summary>
        /// <param name="series"></param>
        /// <param name="row"></param>
        private void AddRunDataToDataSeries(DataSeries series, EIRow row)
        {
            string unit = "";

            if ((row["fdVariableUnit"] != null) && (!row["fdVariableUnit"].ToString().Trim().Equals("")))
            {
                unit = "(" + row["fdVariableUnit"].ToString().Trim() + ")";
            }

            series.Definition.AxisName = row["fdVariableName"].ToString().Trim();
            series.LegendLabel = row["fdVariableName"].ToString().Trim() + unit;

            string _fdMaxValue = "0";
            string _fdMinValue = "0";
            string _fdAvgValue = "0";
            if (null != row["fdMaxValue"] && !"".Equals(row["fdMaxValue"].ToString().Trim()))
            {
                _fdMaxValue = row["fdMaxValue"].ToString().Trim();
            }
            if (null != row["fdMinValue"] && !"".Equals(row["fdMinValue"].ToString().Trim()))
            {
                _fdMinValue = row["fdMinValue"].ToString().Trim();
            }
            if (null != row["fdAvgValue"] && !"".Equals(row["fdAvgValue"].ToString().Trim()))
            {
                _fdAvgValue = row["fdAvgValue"].ToString().Trim();
            }
            double maxValue = Double.Parse(_fdMaxValue);
            double minValue = Double.Parse(_fdMinValue);
            double avgValue = Double.Parse(_fdAvgValue);

            series.Add(new DataPoint(maxValue) { XCategory = "最大值" });
            series.Add(new DataPoint(minValue) { XCategory = "最小值" });
            series.Add(new DataPoint(avgValue) { XCategory = "平均值" });
        }

        /// <summary>
        /// 点击图表类型按钮时的事件响应
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Btn_Click(object sender, RoutedEventArgs e)
        {
            Button btn = sender as Button;

            if (btn != null)
            {
                btn.Focus();

                if (chartType.Equals(btn.Tag.ToString().Trim()))
                {
                    return;
                }
                else
                {
                    chartType = btn.Tag.ToString().Trim();
                }
            }
            else
            {
                return;
            }

            switch (chartType)
            {
                case "Bar":
                    BindDataToRunChart(this.deviceItemsInfoGrid.EIBlock, this.runChart, Common.CHART_BAR);
                    BindDataToLifeChart(this.lifeInfoGrid.EIBlock, this.lifeChart, Common.CHART_BAR);
                    break;
                case "Line":
                    BindDataToRunChart(this.deviceItemsInfoGrid.EIBlock, this.runChart, Common.CHART_LINE);
                    BindDataToLifeChart(this.lifeInfoGrid.EIBlock, this.lifeChart, Common.CHART_LINE);
                    break;
                case "Horizontal Bar":
                    BindDataToRunChart(this.deviceItemsInfoGrid.EIBlock, this.runChart, Common.CHART_HORIZONTALBAR);
                    BindDataToLifeChart(this.lifeInfoGrid.EIBlock, this.lifeChart, Common.CHART_HORIZONTALBAR);
                    break;
                case "Pie":
                    BindDataToRunChart(this.deviceItemsInfoGrid.EIBlock, this.runChart, Common.CHART_PIE);
                    BindDataToLifeChart(this.lifeInfoGrid.EIBlock, this.lifeChart, Common.CHART_PIE);
                    break;
                default:
                    BindDataToRunChart(this.deviceItemsInfoGrid.EIBlock, this.runChart, Common.CHART_BAR);
                    BindDataToLifeChart(this.lifeInfoGrid.EIBlock, this.lifeChart, Common.CHART_BAR);
                    break;
            }
        }

        /// <summary>
        /// 点击运行数据记录时，刷新饼状图
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void deviceItemsInfoGrid_SelectionChanged(object sender, SelectionChangeEventArgs e)
        {
            EIRow selectRow = this.deviceItemsInfoGrid.EIBlock.GetRow(this.deviceItemsInfoGrid.SelectedIndex);

            if ((selectRow != null) && (chartType.Equals(Common.CHART_PIE)))
            {
                EIBlock block = new EIBlock("runDataResult");
                Common.AddColumnToBlock(block, "fdEquipmentCode");
                Common.AddColumnToBlock(block, "fdEquipmentName");
                Common.AddColumnToBlock(block, "fdVariableName");
                Common.AddColumnToBlock(block, "fdMaxValue");
                Common.AddColumnToBlock(block, "fdMaxRecordtime");
                Common.AddColumnToBlock(block, "fdMinValue");
                Common.AddColumnToBlock(block, "fdMinRecordtime");
                Common.AddColumnToBlock(block, "fdAvgValue");

                block.AddRow(selectRow);

                BindDataToRunChart(block, this.runChart, Common.CHART_PIE);
            }
        }

        #endregion

        #region 点击树目录响应处理

        /// <summary>
        /// 点击树目录节点事件响应
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void DeviceSystemTree_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
        {
            if ((sender as EFTree).SelectedItem == null)
                return;

            Common.ClearChart(this.runChart);
            Common.ClearChart(this.lifeChart);

            checkedItems.Clear();

            ClearEFGridData(this.lifeInfoGrid, "lifeDataResult");
            ClearEFGridData(this.deviceItemsInfoGrid, "runDataResult");

            this.deviceItemsGrid.Children.Clear();

            this.deviceGrid.ItemsSource = null;

            EFTreeItem selectItem = (sender as EFTree).SelectedItems[0] as EFTreeItem;
            IList<EIRow> queryList = new List<EIRow>();

            if (selectItem.ParentItem != null)
            {
                if (selectItem.ParentItem.ParentItem != null)
                {
                    //EFWindow.Alert("生产单元节点！");
                    EIRow row = selectItem.ItemObject as EIRow;
                    queryList.Add(row);
                }
                else
                {
                    //EFWindow.Alert("生产系统节点！");
                    AddTreeItems(queryList, selectItem);
                }
            }
            else
            {
                //if (selectItem.IsRootItem)
                //    EFWindow.Alert("矿井节点！");
                AddTreeItems(queryList, selectItem);
            }

            EIBlock block = new EIBlock("queryBlock");
            Common.AddColumnToBlock(block, "fdKeyId");

            if (queryList.Count > 0)
            {
                AddQueryBlock(block, queryList);
                QueryDeviceRunInfo(block);
            }

        }

        /// <summary>
        /// 添加EFTreeItem下的所有叶子节点
        /// </summary>
        /// <param name="list"></param>
        /// <param name="treeItem"></param>
        private void AddTreeItems(IList<EIRow> list, EFTreeItem treeItem)
        {
            if (treeItem.HasItems)
            {
                ItemCollection childItems = treeItem.Items;

                for (int i = 0; i < childItems.Count; i++)
                {
                    EFTreeItem item = (EFTreeItem)childItems[i];

                    if (item.HasItems)
                    {
                        ItemCollection nextChildItems = item.Items;

                        for (int j = 0; j < nextChildItems.Count; j++)
                        {
                            EFTreeItem nextItem = (EFTreeItem)nextChildItems[j];

                            EIRow nextRow = nextItem.ItemObject as EIRow;
                            list.Add(nextRow);
                        }
                    }
                    else
                    {
                        if ((item.ParentItem != null) && (!item.ParentItem.IsRootItem))
                        {
                            EIRow row = item.ItemObject as EIRow;
                            list.Add(row);
                        }
                    }
                }
            }
            else
            {
                return;
            }
        }

        /// <summary>
        /// 拼接查询字段
        /// </summary>
        /// <param name="list"></param>
        /// <param name="treeItem"></param>
        private void AddQueryBlock(EIBlock block, IList<EIRow> list)
        {
            string euqipmentId = "'" + list[0]["fdKeyId"].ToString().Trim() + "'";

            for (int i = 1; i < list.Count; i++)
            {
                euqipmentId = euqipmentId + ", '" + list[i]["fdKeyId"].ToString().Trim() + "'";
            }

            EIRow row = new EIRow();
            row.Add("fdKeyId", euqipmentId);

            block.AddRow(row);
        }

        #endregion

        #region 辅助函数

        /// <summary>
        /// 清除EFGrid控件显示的内容
        /// </summary>
        /// <param name="gridName"></param>
        /// <param name="blockName"></param>
        private void ClearEFGridData(EFGrid gridName, string blockName)
        {
            EIInfo info = new EIInfo();

            EIBlock block = new EIBlock(blockName);

            info.AddBlock(block);

            gridName.ItemsSource = null;
            gridName.UpdateData(info);
        }


        #endregion

















    }
}
